const app = getApp();
import { getUserInfo,setUserInfo } from '../../utils/store';
import api from "../../utils/apiInstance"
const {  moment } = app;
Page({
  data: {
    baseUrl: app.globalData.baseUrl,
    baseDomain: app.globalData.baseDomain,
    fileUrl: app.globalData.fileUrl,
    searchParam:{},
    sapId: '',
    staffId: '',
    cardList: [],
    courseIndex: null,
    projectType:0,
    isKeJianShow:false,
    isOutLink:false,
    isSignShow:false,
    deptList:[],
    bigSearchShow:false,
    sexList:['男','女'],
    educationalBackgroundIndex:'',
    educationalBackgroundList:['博士','硕士','本科','大专','中专','高中','初中','小学','其他'],
    signData:{},
    currentItem:{}, //当前选中的课程
    userinfo:{},
    form:{
      name:getUserInfo().siocCnName,
      dateBoard:app.moment().format('YYYY-MM-DD'),
    },
    sanJiKaConst:{
      MonthlyTrainingPlan:1,
      WorkshopTraining:2,
      TeamTraining:3
    }
  },
  
  async loadData () {
    var that = this;
    console.log("查询培训参数",{
      projectType:that.data.projectType||'',
      sapId: that.data.sapId||'',
      ...that.data.searchParam
    })
    let res = [];
    //直接跳转过来的 直接查询某一个课程
    if(that.data.isOutLink){
      res = await api.get(`/v1/openApi/staff/course/${that.data.searchParam.id}?type=2`)
    }
    else{
      res = await api.post(`/v1/openApi/staff/myCourse`,{
        projectType:that.data.projectType||'',
        staffId: that.data.staffId||'',
        ...that.data.searchParam
      })
    }
    this.getAllDept();
      var data = res.rows|| [res.data];

        for(let item of data){
          let tempArray = [];

          let examRes = await app.apiInstance.post(`/v1/openApi/staff/pass/examine/${item.id}/${item.courseList[0].key}/${getUserInfo().staffId}`)
          console.log('item',item)
          //逻辑变更 isStaffSign 0 未签到 1 已经签到未考试 2 已经签到已经考试未签名 3 已经签名

            // SIGN_FLOW_START 0签署流程开启通知
            // *SIGN_FLOW_SIGNED 1签署方签要完成通知
            // *
            // *SIGN_FLOW_FINISH 2签署流程完成通知
            // *SIGN_FLOW_OVERTIME 3签署流程过期通知
            // *SIGN_FLOW_EXPIRE_REMIND 4签署截止前通知
            // *SIGN_FLOW_REFUSE 5签署方拒签通知
            // *SI6N_FLOW_CANCEL6 签要流程作废通知
            // *SIGNED_FLOW_SI6N_FAILED 9签署失败

          if(examRes.data){
            if(examRes.data.signStatus==2){
              item.isStaffSign=3 //已经签名
            }
            else{
              item.isStaffSign=2 //已经签到
            }
          }
          else{
            
            if(item.staffSign && item.staffSign.staffId == that.data.staffId){
             
              item.isStaffSign=1 //已经签到
            }
            else{
              item.isStaffSign=0 //未签到
            }
          }
          item.examId = examRes?.data?.id; //补上examid
          if(item.isStaffSign!=0&&item.staffSign?.images?.length>0){
            item.staffSign.images.forEach(inneritem => {
              tempArray.push({url:inneritem, closeable:false})
            });

            item.staffSign.images = tempArray
          }
          else{
            item.staffSign = {
              images:[]
            }
          }
        }

       console.log('data',data)
        that.setData({
          cardList: data
        })
        
   
  },
  onLoad: function (params) {
    const initParam = this.selectComponent("#searchTab").data

    //扫码进入的情况
    if(params.id){
      this.setData({
        searchParam: {
          id:params.id
        },
        isOutLink:true,
        sapId: wx.getStorageSync('userinfo').siocSapNo,
        staffId: wx.getStorageSync('userinfo').staffId
       })
       console.log('this.data.searchParam',this.data.searchParam)
    }
    
    else if(params.urlParams){
      console.log('params.urlParams',params.urlParams)
      try{
        this.setData({
          searchParam: {
            id: JSON.parse(params.urlParams).id
          },
          isOutLink:true,
          sapId: wx.getStorageSync('userinfo').siocSapNo,
          staffId: wx.getStorageSync('userinfo').staffId
        })
      }catch(err){
          wx.showModal({
            title: '提示',
            content: '无法解析JSON',
            success: function(res) {
              
            }
        })
        return
       
      }
    }
    else{
      this.setData({
        searchParam: {
          endTime:initParam.currentTime[1],
          startTime:initParam.currentTime[0],
          sign:initParam.signStatus
        },
        projectType:params.type,
        sapId: wx.getStorageSync('userinfo').siocSapNo,
        staffId: wx.getStorageSync('userinfo').staffId
      })
    }

   
    this.loadData();
  },

  showKeJian(card){
    const that = this
    wx.navigateTo({
      url: `/pages/file-list/file-list?id=${card.target.dataset.item.id}`,
    });
    // this.setData({
    //   isKeJianShow:!this.data.isKeJianShow
    // })
  },

  searchSelect(e) {
   
    this.setData({
      ['form.dept']:e.detail.name
    })
  },

  uploadImages: function (event) {
    let index = event.currentTarget.dataset.index;
    let that = this;
    wx.chooseMedia({
      count: 9, // 默认9  
      mediaType: ['image'],
      sourceType: ['camera'],
      camera: 'back', // 使用后置摄像头  
      success: function (res) {
        var path = res.tempFiles[0].tempFilePath;
        wx.showLoading({
          title: '签到图片上传中', // 提示的内容  
          mask: true, // 是否显示透明蒙层，防止触摸穿透  
        });
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload',
          filePath: path,
          name: 'file',
          success(res) {
            let fileInfo = JSON.parse(res.data);
            let fileName = fileInfo.fileName;
            var list = that.data.cardList;
            if (!list[index].imageList) {
              list[index].images = [];
              list[index].imageList = [];
            }
            list[index].images.push(fileName);
            list[index].imageList.push(path);
            that.setData({
              cardList: list
            });
            wx.hideLoading();
          },
          fail(err) {
            wx.hideLoading();
            wx.showToast({
              title: "上传失败",
              icon: 'none',
              duration: 3000
            });
          }
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "签到失败",
          icon: 'none',
          duration: 3000
        });
      }
    });

    // this.saveSignnature(this,item);
  },

 

  //搜索返回
  doSearch(res){

    let newParams = {
      endTime:res.detail.currentTime[1],
      startTime:res.detail.currentTime[0],
      sign:Boolean(+res.detail.signStatus),
      pass:Boolean(+res.detail.achievementType)
    }
    //全部要删去参数
    if(res.detail.achievementType=="2"){
      delete newParams.pass
    }
    if(res.detail.signStatus=="2"){
      delete newParams.sign
    }

    this.setData({
      searchParam: newParams
    })

    this.loadData();
  },

  DateChange: function (e) {
    this.setData({
      ['form.dateBoard']: e.detail.value
    })
  },

  nameChange(e){
    this.setData({
      ['form.name']:e.detail.value,
    })
  },

  deptChange(e){
    this.setData({
      ['form.dept']:e.detail.value,
    })
  },

  phoneChange(e){
    this.setData({
      ['form.phone']:e.detail.value,
    })
  },

  ageChange(e){
    this.setData({
      ['form.age']:e.detail.value,
    })
  },

  teamGroupChange(e){
    this.setData({
      ['form.teamGroup']:e.detail.value,
    })
  },

  postChange(e){
    this.setData({
      ['form.post']:e.detail.value,
    })
  },

  idCardChange(e){
    this.setData({
      ['form.idCard']:e.detail.value,
    })
  },

  phoneChange(e){
    this.setData({
      ['form.phone']:e.detail.value,
    })
  },

  sexChange(e){
    this.setData({
      ['form.sex']:this.data.sexList[e.detail.value],
    })
  },

  educationalBackgroundChange(e){

    this.setData({
      educationalBackgroundIndex: e.detail.value,
      ['form.educationalBackground']:this.data.educationalBackgroundList[e.detail.value],
    })
  },

  //签到前
  staffSignIn: async function (event) {
    let item = event.currentTarget.dataset.item;
    this.setData({
      currentItem:item
    })
    const imageList = this.selectComponent(`#imageUp${event.currentTarget.dataset.index}`).data.imageList
    if (imageList && imageList.length > 0) {
        //厂级培训查询三级卡信息如果有就之前去签名 如果没有 让他填写
        if(item.projectType == 'MonthlyTrainingPlan'){
          const res = await api.get(`/v1/openApi/employee/search/staff/sapId/${getUserInfo().staffId}`);
          if(!res.data.signInfo){
            this.setData({
              isSignShow: true,
              signData:{item, imageList},
              ['form.dept']:res.data.staffInfo.dept,
              ['form.post']:res.data.staffInfo.post,
            })
          }else{
            this.setData({
              userinfo:res.data.signInfo
            })
            setUserInfo(Object.assign({},getUserInfo(),{siocPhone:res.data.signInfo.phone}))
            this.saveSignnature(this, item, imageList, res.data.signInfo);
          }
        }else{
          this.saveSignnature(this, item, imageList, null);
        }
    } else {
      wx.showToast({
        title: "请先上传现场图片",
        icon: 'none',
        duration: 3000
      });
    }
  },

  // 个人信息提交
  infoSubmit(){
    if(!this.data.form.name){
      wx.showToast({
        title: '请输入姓名！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if(!this.data.form.phone){
      wx.showToast({
        title: '请输入手机号！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if(!this.data.form.age){
      wx.showToast({
        title: '请输入年龄！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if(!this.data.form.educationalBackground){
      wx.showToast({
        title: '请输入学历！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if(!this.data.form.dept){
      wx.showToast({
        title: '请输入所在部门！',
        icon: 'none',
        duration: 3000
      });
      return
    }
    if(!this.data.form.post){
      wx.showToast({
        title: '请输入岗位！',
        icon: 'none',
        duration: 3000
      });
      return
    }

    this.setData({
      isSignShow:false,
      ['form.staffId']: getUserInfo().staffId
    })
    setUserInfo(Object.assign({},getUserInfo(),{siocPhone:this.data.form.phone}))
    this.saveSignnature(this, this.data.signData.item, this.data.signData.imageList, this.data.form);
  },

  //考试签名 补签
  testSignIn(event){
    const that = this;
    let item = event.currentTarget.dataset.item;
    this.setData({
      currentItem:item
    })

    //考试签名
    that.kaoShiQianM()
  },
  testSignIn2(event){
    let examId = event.currentTarget.dataset.item.examId;
    let projectType = event.currentTarget.dataset.item.projectType;
    wx.redirectTo({
      url: '/pages/my-signature2/my-signature2?examId=' + examId + '&projectType=' + projectType
    })
  },

  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        var data = res.data;
        that.setData({
          deptList: data.data.map(item=> {return {name:item}})
        })
      }
    });
  },

  //签到
  saveSignnature: function (that, item, imageList, info) {

    const tempArray = [];
    imageList.forEach(item=>{
      tempArray.push(item.url);
    })
    if(null != info && null != info.dataBoard){
      info.dateBoard = info.dateBoard+" 00:00:00"
    }
    let data = {
      sapId: that.data.sapId,
      staffId: that.data.staffId,
      trainId: item.id,
      type: 2,//员工签到
      images: tempArray,
      staffSignPersonInfo:info
    };
    wx.showLoading({
      title: '签到中', // 提示的内容  
      mask: true, // 是否显示透明蒙层，防止触摸穿透  
    });
    wx.request({
      url: that.data.baseUrl + '/v1/openApi/sign',
      method: 'POST',
      data: data,
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {

        wx.hideLoading();
        if (res.data.code != 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          });
          return;
        }

        else{
         
        }

        that.loadData();
      }, fail(res) {
        wx.hideLoading();
        wx.showToast({
          title: '签名保存失败，请联系管理人员！',
          icon: 'none',
          duration: 3000
        });
      }
    });
  },
  
  //发起考试签名
  async kaoShiQianM(){
    //获取examid 
      console.log('this.data.currentItem',this.data.currentItem)
      console.log('111111',getUserInfo())

      const res1 = await api.get(`/v1/openApi/employee/search/staff/sapId/${getUserInfo().staffId}`);
    if(!res1.data.signInfo){
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    //签名接口
    const res = await app.apiInstance.post(`/v1/openApi/staff/examines/${this.data.currentItem.examId}?account=${res1.data.signInfo.phone}&name=${getUserInfo().siocCnName}`, this.data.form)
    
    if(res.data){
      this.setData({
        isSignShow:false
      })
      console.log('res.data',res.data)
      wx.navigateTo({
        url: `/pages/comWebView/comWebView?url=${encodeURIComponent(res.data)}`
      });
    }
  },


  

  coursebindChange: function (event) {
    const that = this;
    var item = event.currentTarget.dataset.item;
    var index = event.detail.value;
    var key = item.courseList[index].key;
    console.log('event',event);
    //培训类型
    wx.setStorageSync('trainType',event?.currentTarget?.dataset?.item?.projectType);
    
    wx.request({
      url: this.data.baseUrl+'/v1/openApi/staff/myQuestion/'+this.data.sapId+'/' +item.id+'/'+key,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        var data=res.data.data;
        if(res.data.code!=200){
          wx.showToast({  
            title: res.data.msg,  
            icon: 'none',  
            duration: 3000  
          });  
          return;
        }
       
        else if(data.value.length==0){
          if(wx.getStorageSync('trainType') == 'TeamTraining'){
            wx.showModal({
              title: '当前无考试，前往三级教育卡签名',
              success(res) {
                that.faQiSanJiQs();
              }
            })
          }
          else{
            wx.showToast({  
              title: '当前无考试',  
              icon: 'none',  
              duration: 3000  
            });  
          }
          
         
          return;
        }
        else{
          wx.redirectTo({
            url: `/pages/my-exma/my-exma?trainId=${item.id}&courseId=${key}&projectType=${that.data.projectType}&sapId=${that.data.sapId}`
          })
        }
      }
    });


    
  },


  //发起三级签署 
  //**
  /* 
  * @param {
  * } data  当前考试的信息
  */
  async faQiSanJiQs() {
    try {
      const bigdata = {};
      //如果是班组级培训 说明3次培训都已经完成了 验证一下 是否通过考试
      if (wx.getStorageSync('trainType') == 'TeamTraining') {
        //工厂级别考试
        const gongChangKs = await api.post(`/v1/openApi/staff/myCourse`, {
          projectType: 'MonthlyTrainingPlan',
          sign: true,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`
        })


        //车间级别考试
        const cheJianKs = await api.post(`/v1/openApi/staff/myCourse`, {
          projectType: 'WorkshopTraining',
          sign: true,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`
        })

        // for (let gongChangItem of gongChangKs.rows) {
        //   let { data } = await api.post(`/v1/openApi/staff/pass/examine/${gongChangItem.id}/${gongChangItem.courseList[0].key}/${getUserInfo().siocSapNo}`)
        //   gongChangItem.examResult = data;
        // }

        // for (let cheJianItem of cheJianKs.rows) {
        //   let { data } = await api.post(`/v1/openApi/staff/pass/examine/${cheJianItem.id}/${cheJianItem.courseList[0].key}/${getUserInfo().siocSapNo}`)
        //   cheJianItem.examResult = data;
        // }
        // //找到考试通过的
        // const gongChangeFindOne = gongChangKs.rows[0]
        // const cheJianFindOne = cheJianKs.rows[0]


        //当前考试信息获取课程信息 班组级
        const banZuKs = await api.post(`/v1/openApi/staff/myCourse`, {
          sign: true,
          endTime: `${moment().format("yyyy-MM-DD")} 23:59:59`,
          startTime: `${moment().subtract(1, 'years').format("yyyy-MM-DD")} 00:00:00`,
          projectType: 'TeamTraining'
        })
        const banZuKsFindOne = banZuKs.rows[0]
        banZuKsFindOne.examResult = bigdata;

        //if (gongChangeFindOne && cheJianFindOne) {
          //发起三级卡签名
          // const staffList = await apiInstance.get(`/v1/openApi/employee/search/staffList`);
          
          const trainDuration1 = moment(gongChangKs.rows[0].endTime).diff(moment(gongChangKs.rows[0].startTime), 'hours')
          const trainDuration2 = moment(cheJianKs.rows[0].endTime).diff(moment(cheJianKs.rows[0].startTime), 'hours')
          const trainDuration3 = moment(banZuKsFindOne.endTime).diff(moment(banZuKsFindOne.startTime), 'hours')
        
          console.log('1111',gongChangKs.rows[0].endTime,gongChangKs.rows[0].startTime)
          console.log('2222',trainDuration1)

          const params = {
            studentName: getUserInfo().siocCnName,
            studentTel: getUserInfo().siocPhone,
            teacherSapId1: gongChangKs.rows[0].teacher,
            teacherSapId2: cheJianKs.rows[0].teacher,
            teacherSapId3: banZuKsFindOne.teacher,
            trainBeginTime1: moment(gongChangKs.rows[0].startTime).format('YYYY-MM-DD HH'),
            trainBeginTime2: moment(cheJianKs.rows[0].startTime).format('YYYY-MM-DD HH'),
            trainBeginTime3: moment(banZuKsFindOne.startTime).format('YYYY-MM-DD HH'),
            trainCreateBy: gongChangKs.rows[0].createBy,
            trainDuration1: gongChangKs.rows[0].trainingDuration,
            trainDuration2: cheJianKs.rows[0].trainingDuration,
            trainDuration3: banZuKsFindOne.trainingDuration,
            trainEndTime1: moment(gongChangKs.rows[0].endTime).format('YYYY-MM-DD HH'),
            trainEndTime2: moment(cheJianKs.rows[0].endTime).format('YYYY-MM-DD HH'),
            trainEndTime3: moment(banZuKsFindOne.endTime).format('YYYY-MM-DD HH'),
            redirectUrl:encodeURIComponent(this.data.baseDomain+'/dcp-t/#/webView?random='+new Date().getTime())
          };

          const res = await api.post(`/esign/wx/signThree`, params)
          wx.navigateTo({
            url: `/pages/comWebView/comWebView?url=${encodeURIComponent(res.data)}`
          });
        //}
      }
    }
    catch (err) {
      console.log('err', err)
      wx.showModal({
        title: '提示',
        content: '发起三级卡信息失败，请尝试重新点击按钮或联系管理人员！',

        success: function (res) {
        
        }
      })
    }
  }
})